# -*- encoding=utf8 -*-
__author__ = "chen"

import json
import os
import threading
import tkinter as tk  # 创建窗口
from airtest.core.api import *
from multiprocessing import Process
from cangbaotu.藏宝图 import cangbaotu



root = tk.Tk()
root.title("任务执行") #设置窗口标题
root.geometry("600x600") #设置窗口尺寸

def run_command(command):
    read_result=[]
    result = os.popen(command).readlines()
    for i in range(len(result)):
        temp = result[i].strip().replace("\t"," ")
        if temp:
            read_result.append(temp)
    print(read_result)
    return read_result
def load_config():
    with open("./config/init_config.json", "r", encoding="utf-8") as f:
        lines = json.load(f)
    devs = lines["dev"]
    device_list = []
    for i in range(len(devs)):
        try:
            if ":" in devs[i]:
                result = run_command(f"adb connect {devs[i]}")
                if devs[i] not in result[0]:
                    continue
            connect_device(f'Android:///{devs[i]}')
            device_list.append(devs[i])
        except:
            print(f"连接异常，请确认设备是否上线：{devs[i]}")
    print(f"连接设备数量：{len(device_list)}")
    return device_list

#############
def check_selection():
    selected_items = []
    for i, var in enumerate(check_vars):
        if var.get() == 1:  # 如果Checkbutton被选中
            selected_items.append(options[i])
    print("Selected items:", selected_items)
    result_label.config(text="选择对象：" + str(selected_items))
    return selected_items

def check_selection_zhuogui():
    selected_items = check_selection()
    # 在这里添加你的下一步动作
    for i in range(len(selected_items)):
        threading.Thread(target=cangbaotu,args=(selected_items[i],)).start()


# 假设这是你的选项列表
options = load_config()

# 创建一个变量列表来跟踪每个Checkbutton的状态
check_vars = [tk.IntVar() for _ in options]

# 遍历选项列表并创建Checkbutton
for i, option in enumerate(options):
    cb = tk.Checkbutton(root, text=option, variable=check_vars[i],justify=tk.CENTER)
    cb.pack(anchor='c')  # 将Checkbutton 中心排列

# 创建一个按钮来检查哪些Checkbutton被选中
check_btn = tk.Button(root, text="选择设备 捉鬼", command=check_selection_zhuogui)
check_btn.pack(pady=20)

result_label_title = tk.Label(root, text="显示结果:",width=500, height=2,bg="#e9faff",justify="left")
result_label_title.pack()
# 创建一个标签，用于显示结果
result_label = tk.Label(root, text="",width=500, height=2,justify='center',pady=20,relief="flat",wraplength=400)
result_label.pack()
if len(options)<1:
    result_label.config(text="选择对象：未找到有效设备")


root.mainloop()